package ch.headshot.photomap.mapper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;

import ch.headshot.photomap.client.exception.MapperException;
import ch.headshot.photomap.client.gpx.Gpx;
import ch.headshot.photomap.client.gpx.Route;
import ch.headshot.photomap.client.gpx.Track;
import ch.headshot.photomap.client.gpx.TrackSegment;
import ch.headshot.photomap.client.gpx.WayPoint;
import ch.headshot.photomap.client.gpx.impl.GpxImpl;

import com.google.gwt.xml.client.XMLParser;

public class WrapperHelper {

	public static Gpx fileToGpx(File file) {
		String string;
		try {
			string = IOUtils.toString(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			throw new MapperException("failed to read file" + file.getAbsolutePath(), e);
		} catch (IOException e) {
			throw new MapperException("failed to read file" + file.getAbsolutePath(), e);
		}
		return new GpxImpl(XMLParser.parse(string).getDocumentElement());
	}

	public static List<WayPoint> readTimedWayPoints(Gpx gpx) {
		List<WayPoint> wayPoints = new ArrayList<WayPoint>(256);
		for (WayPoint point : gpx.getWayPoints()) {
			addToListIfTimed(point, wayPoints);
		}
		for (Route route : gpx.getRoutes()) {
			for (WayPoint point : route.getPoints()) {
				addToListIfTimed(point, wayPoints);
			}
		}
		for (Track track : gpx.getTracks()) {
			for (TrackSegment seg : track.getSegments()) {
				for (WayPoint point : seg.getPoints()) {
					addToListIfTimed(point, wayPoints);
				}
			}
		}
		return wayPoints;
	}

	private static void addToListIfTimed(WayPoint point, List<WayPoint> list) {
		if (point.getTime() != null) {
			list.add(point);
		}
	}

	public static File[] listImagesInFolder(File folder) {
		return folder.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.endsWith(".jpg") || name.endsWith(".jpeg");
			}
		});
	}
}
